/* This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.gnarly;

import java.net.ServerSocket;
import java.net.Socket;

import com.gnarly.global.ClientManager;

/**
 * Listener.java
 * 
 * Listens for incoming connections
 * 
 * @author gnarly
 */
public class Server implements Runnable {
	
	public Server() {
	}
	
	public void run() {
		try {
			final ServerSocket serverSocket = new ServerSocket(Main.SERVER_LISTENER_PORT);
			System.out.println("Telnet Server started on port: " + Main.SERVER_LISTENER_PORT + ".");
			while (true) {
				final Socket socket = serverSocket.accept();
				socket.setTcpNoDelay(true);
				final String host = socket.getInetAddress().getHostName();
				if (!FloodProtection.has(host, 1)) {
					System.out.println("Accepted connection from: " + host);
					ClientManager.getSingleton().newClient(socket);
					FloodProtection.add(host);
				} else {
					System.out.println("Rejected connection from: " + host);
					socket.close();
				}
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

}